package com.cloudfun.campusshare.configuration.jpa.restriction;

import com.cloudfun.campusshare.configuration.jpa.specification.SpecificationModel;
import com.cloudfun.campusshare.configuration.jpa.util.ConvertUtils;
import com.cloudfun.campusshare.configuration.jpa.util.PropertyFilter;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;

/**
 * @author 王溪源
 * @ClassName: PredicateMultipeValueSupport
 * @Description:
 **/
public abstract class PredicateMultipeValueSupport extends PredicateSingleValueSupport {
    public Object convertMatchValue(String value, Class<?> type) {
        String[] result = StringUtils.splitByWholeSeparator (value, getAndValueSeparator ());
        return ConvertUtils.convert (result, type);
    }

    public Predicate build(PropertyFilter filter, SpecificationModel model) {
        Object value = convertMatchValue (filter.getMatchValue (), filter.getPropertyType ());
        Predicate predicate = null;
        if (filter.hasMultiplePropertyNames ()) {
            Predicate orDisjunction = model.getBuilder ().disjunction ();
            for (String propertyName : filter.getPropertyNames ()) {
                orDisjunction.getExpressions ().add (build (propertyName, value, model));
            }
            predicate = orDisjunction;
        } else {
            predicate = build (filter.getSinglePropertyName (), value, model);
        }
        return predicate;
    }

    @Override
    public Predicate build(Path<?> path, Object value, CriteriaBuilder builder) {
        return buildRestriction (path, (Object[]) value, builder);
    }

    public abstract Predicate buildRestriction(Path<?> path, Object[] value, CriteriaBuilder builder);
}
